/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package View.components;

import Model.Producto;
import Presenter.ProductoPresenter;
import Principals.Validadores;
import View.ventas.Frm_RegistrarPedido;
import java.awt.Dimension;
import java.awt.Point;
import java.math.BigDecimal;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author walter
 */
public class PopUpNuevoProducto extends javax.swing.JDialog {
    private JDesktopPane pnl ;
    private Validadores val = new Validadores() ;
    /**
     * Creates new form Frm_RegistrarProducto
     */
    public PopUpNuevoProducto(){
        initComponents();
        val.desactivarAccionPegar(txtNombre);
        val.desactivarAccionPegar(txtPrecioCosto);
        val.desactivarAccionPegar(txtPrecioLista);
        val.desactivarAccionPegar(txtStock);          
    }
    
    public PopUpNuevoProducto( JFrame parent ){
        super( parent , true ) ;
        if( parent != null ){
          Dimension parentSize = parent.getSize() ; 
          Point p = parent.getLocation() ; 
          setLocation( p.x + parentSize.width / 4 , p.y + parentSize.height / 4 ) ;
        }
        initComponents() ;
        this.pack() ;
        this.setVisible( true ) ;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
   @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
       pnl = new JDesktopPane() ;
        jToolBar1 = new javax.swing.JToolBar();
        btnToolNuevo = new javax.swing.JButton();
        btnToolModificar = new javax.swing.JButton();
        btnToolGuardar = new javax.swing.JButton();
        btnToolEliminar = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        btnToolLimpiar = new javax.swing.JButton();
        btnToolBuscar = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        btnToolCancelar = new javax.swing.JButton();
        jSeparator3 = new javax.swing.JToolBar.Separator();
        pnlRegistrarProducto = new javax.swing.JPanel();
        lblNombre = new javax.swing.JLabel();
        lblPrecioCosto = new javax.swing.JLabel();
        lblPrecioLista = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        lblStock = new javax.swing.JLabel();
        txtPrecioCosto = new javax.swing.JTextField();
        txtPrecioLista = new javax.swing.JTextField();
        txtStock = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);
        jToolBar1.setBorderPainted(false);

        btnToolNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Nuevo.png"))); // NOI18N
        btnToolNuevo.setEnabled(false);
        btnToolNuevo.setFocusable(false);
        btnToolNuevo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolNuevo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolNuevoActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolNuevo);

        btnToolModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Editar.png"))); // NOI18N
        btnToolModificar.setEnabled(false);
        btnToolModificar.setFocusable(false);
        btnToolModificar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolModificar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolModificarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolModificar);

        btnToolGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Guardar.png"))); // NOI18N
        btnToolGuardar.setFocusable(false);
        btnToolGuardar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolGuardar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolGuardarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolGuardar);

        btnToolEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Eliminar.png"))); // NOI18N
        btnToolEliminar.setEnabled(false);
        btnToolEliminar.setFocusable(false);
        btnToolEliminar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolEliminar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolEliminarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolEliminar);
        jToolBar1.add(jSeparator2);

        btnToolLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Limpiar.png"))); // NOI18N
        btnToolLimpiar.setFocusable(false);
        btnToolLimpiar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolLimpiar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolLimpiarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolLimpiar);

        btnToolBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Buscar.png"))); // NOI18N
        btnToolBuscar.setFocusable(false);
        btnToolBuscar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolBuscar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolBuscarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolBuscar);
        jToolBar1.add(jSeparator1);

        btnToolCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Cancelar.png"))); // NOI18N
        btnToolCancelar.setFocusable(false);
        btnToolCancelar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolCancelar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolCancelarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolCancelar);
        jToolBar1.add(jSeparator3);

        pnlRegistrarProducto.setBorder(javax.swing.BorderFactory.createTitledBorder("Registro"));

        lblNombre.setText("Nombre*:");

        lblPrecioCosto.setText("Precio Costo*:");

        lblPrecioLista.setText("Precio Lista*:");

        txtNombre.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtNombreKeyTyped(evt);
            }
        });

        lblStock.setText("Stock*:");

        txtPrecioCosto.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtPrecioCostoKeyTyped(evt);
            }
        });

        txtPrecioLista.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtPrecioListaKeyTyped(evt);
            }
        });

        txtStock.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtStockKeyTyped(evt);
            }
        });

        jLabel1.setText("S/.");

        jLabel2.setText("S/.");

        javax.swing.GroupLayout pnlRegistrarProductoLayout = new javax.swing.GroupLayout(pnlRegistrarProducto);
        pnlRegistrarProducto.setLayout(pnlRegistrarProductoLayout);
        pnlRegistrarProductoLayout.setHorizontalGroup(
            pnlRegistrarProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlRegistrarProductoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlRegistrarProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlRegistrarProductoLayout.createSequentialGroup()
                        .addGroup(pnlRegistrarProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlRegistrarProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlRegistrarProductoLayout.createSequentialGroup()
                                    .addComponent(lblPrecioCosto)
                                    .addGap(18, 18, 18))
                                .addGroup(pnlRegistrarProductoLayout.createSequentialGroup()
                                    .addComponent(lblNombre)
                                    .addGap(36, 36, 36)))
                            .addGroup(pnlRegistrarProductoLayout.createSequentialGroup()
                                .addComponent(lblStock)
                                .addGap(47, 47, 47)))
                        .addGroup(pnlRegistrarProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(pnlRegistrarProductoLayout.createSequentialGroup()
                                .addGroup(pnlRegistrarProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(txtStock, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 110, Short.MAX_VALUE)
                                    .addComponent(txtPrecioLista, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtPrecioCosto, javax.swing.GroupLayout.Alignment.LEADING))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(pnlRegistrarProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel2)))
                            .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(lblPrecioLista))
                .addContainerGap(90, Short.MAX_VALUE))
        );
        pnlRegistrarProductoLayout.setVerticalGroup(
            pnlRegistrarProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlRegistrarProductoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlRegistrarProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNombre)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(pnlRegistrarProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblPrecioCosto)
                    .addComponent(txtPrecioCosto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(pnlRegistrarProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblPrecioLista)
                    .addComponent(txtPrecioLista, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(pnlRegistrarProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblStock)
                    .addComponent(txtStock, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(21, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(pnl);
        pnl.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlRegistrarProducto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jToolBar1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlRegistrarProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(5, 5, 5))
        );
        this.add( pnl ) ;
    }// </editor-fold>                                

    private void btnToolCancelarActionPerformed(java.awt.event.ActionEvent evt) {                                                
        this.setVisible( false ) ;
    }                                               

    private void btnToolLimpiarActionPerformed(java.awt.event.ActionEvent evt) {                                               
        limpiar() ;
    }                                              

    private void btnToolNuevoActionPerformed(java.awt.event.ActionEvent evt) {                                             

    }                                            

    private void btnToolModificarActionPerformed(java.awt.event.ActionEvent evt) {                                                 

    }                                                

    private void btnToolBuscarActionPerformed(java.awt.event.ActionEvent evt) {                                              
        
    }                                             

    private void btnToolEliminarActionPerformed(java.awt.event.ActionEvent evt) {                                                
        
    }                                               

     private void btnToolGuardarActionPerformed(java.awt.event.ActionEvent evt) {                                               

            try {
                String nombre = txtNombre.getText();
                String pc = txtPrecioCosto.getText();
                String pl = txtPrecioLista.getText();
                String s = txtStock.getText();
                BigDecimal precioCosto = new BigDecimal(0);
                BigDecimal precioLista = new BigDecimal(0);

                int stock = 0;
                String msj_error = "";
                boolean error = false;
                boolean pc_val=false;
                boolean pl_val=false;

                if (nombre.isEmpty() || pc.isEmpty() || pl.isEmpty() || s.isEmpty()) {
                    msj_error = "Debe ingresar todos los campos obligatorios.";
                    error = true;
                    //JOptionPane.showMessageDialog(this, "Por favor ingresar todos los campos");
                }
            if (!nombre.isEmpty() && nombre.length() > 20) {
                if (error) {
                    msj_error = msj_error.concat("\n");
                }
                msj_error = msj_error.concat("El campo Nombre debe ser máximo de 20 caracteres.");
                error = true;
            }                 
                if (!pc.isEmpty()) {
                    
                    if(val.validaOcurrencias('.', txtPrecioCosto.getText()) > 1){
                        if (error) {
                            msj_error = msj_error.concat("\n");
                        }
                        msj_error = msj_error.concat("Debe ingresar un Precio de Costo válido .");
                        error = true;
                    }
                    else if (new BigDecimal(txtPrecioCosto.getText()).compareTo(new BigDecimal(999999.99)) == 1){  
                        if (error) {
                            msj_error = msj_error.concat("\n");
                        }
                        msj_error = msj_error.concat("Debe ingresar un Precio de Costo menor a 9999999.99 .");
                        error = true;   
                         
                    }
                    else{
                        pc_val=true;
                        precioCosto = new BigDecimal(txtPrecioCosto.getText());
                    }
                }
                
                if (!pl.isEmpty()) {
                    
                    if(val.validaOcurrencias('.', txtPrecioLista.getText()) > 1){        
                        if (error) {
                            msj_error = msj_error.concat("\n");
                        }
                        msj_error = msj_error.concat("Debe ingresar un Precio de Lista válido .");
                        error = true;
                    }
                    else if (new BigDecimal(txtPrecioLista.getText()).compareTo(new BigDecimal(999999.99)) == 1){  
                        if (error) {
                            msj_error = msj_error.concat("\n");
                        }
                        msj_error = msj_error.concat("Debe ingresar un Precio de Lista menor a 9999999.99 .");
                        error = true;   
                         
                    }
                    else{
                        precioLista = new BigDecimal(txtPrecioLista.getText());
                        pl_val=true;
                    }
                }

                if (!pc.isEmpty() && !pl.isEmpty() && pc_val && pl_val && precioCosto.compareTo(precioLista) == 1) {
                    if (error) {
                        msj_error = msj_error.concat("\n");
                    }
                    msj_error = msj_error.concat("Debe ingresar un Precio de Lista mayor al Precio de Costo.");
                    error = true;
                }
                if (!s.isEmpty() && (stock=Integer.parseInt(txtStock.getText())) == 0) {
                    if (error) {
                        msj_error = msj_error.concat("\n");
                    }
                    msj_error = msj_error.concat("El Stock debe ser mayor que cero.");
                    error = true;
                }  
                
                if (error) {
                    JOptionPane.showMessageDialog(this, msj_error);
                } else {
                    int respuesta = JOptionPane.showConfirmDialog(this, "Está seguro de registrar el producto", "Guardar", JOptionPane.OK_CANCEL_OPTION);
                    switch (respuesta) {
                        case JOptionPane.OK_OPTION:
                            Producto prod =ProductoPresenter.registrarProducto(nombre, precioCosto, precioLista, stock);
                            JOptionPane.showMessageDialog(this, "Se registró el producto.");
                            limpiar();
                            regresar(prod);
                            break;
                        case JOptionPane.CANCEL_OPTION:
                            break;
                    }
                    
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "No se pudo realizar la transacción.");
                System.out.println("MENSAJE DE ERROR:" + e);
            }

    }                                              

    private void txtNombreKeyTyped(java.awt.event.KeyEvent evt) {                                   
        val.validaCaracteresRaros(evt);
        val.validaMaxSize(evt, 20, txtNombre.getText());
        txtNombre.setTransferHandler(null);
    }                                  

    private void txtPrecioCostoKeyTyped(java.awt.event.KeyEvent evt) {                                        
        val.validaDoublePositivo(evt);
        val.validaMaxSize(evt, 9, txtPrecioCosto.getText());
        txtPrecioCosto.setTransferHandler(null);
    }                                       

    private void txtPrecioListaKeyTyped(java.awt.event.KeyEvent evt) {                                        
        val.validaDoublePositivo(evt);
        val.validaMaxSize(evt, 9, txtPrecioLista.getText());
        txtPrecioLista.setTransferHandler(null);
    }                                       

    private void txtStockKeyTyped(java.awt.event.KeyEvent evt) {                                  
        val.validaSoloNumeros(evt);
        val.validaMaxSize(evt, 7, txtStock.getText());
        txtStock.setTransferHandler(null);

    }                                 
    private void limpiar() {
        txtNombre.setText("");
        txtPrecioCosto.setText("");
        txtPrecioLista.setText("");
        txtStock.setText("");
    }
    
    private void regresar( Producto prod ){
        Index p = ( Index )( this.getParent() ) ;
        if( ( p.getContainer().getClass().toString().equals( "class View.ventas.Frm_RegistrarPedido" ) ) ){
            try{
                this.setVisible( false ) ;
                Frm_RegistrarPedido owner = (Frm_RegistrarPedido)p.getContainer() ;
                owner.actualizarDatosProducto( prod ) ;
            }
            catch (Exception e){
            }
        }
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btnToolBuscar;
    private javax.swing.JButton btnToolCancelar;
    private javax.swing.JButton btnToolEliminar;
    private javax.swing.JButton btnToolGuardar;
    private javax.swing.JButton btnToolLimpiar;
    private javax.swing.JButton btnToolModificar;
    private javax.swing.JButton btnToolNuevo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JToolBar.Separator jSeparator3;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JLabel lblNombre;
    private javax.swing.JLabel lblPrecioCosto;
    private javax.swing.JLabel lblPrecioLista;
    private javax.swing.JLabel lblStock;
    private javax.swing.JPanel pnlRegistrarProducto;
    private javax.swing.JTextField txtNombre;
    private javax.swing.JTextField txtPrecioCosto;
    private javax.swing.JTextField txtPrecioLista;
    private javax.swing.JTextField txtStock;
    // End of variables declaration         
}
